package httputil

import (
	"bytes"
	"encoding/json"
	"gitee.com/Rankx_code/ego-component/utils/errorx"
	"io/ioutil"
	"net/http"
	"time"
)

var client = http.Client{
	Timeout: 5 * time.Second,
}

// 发送post请求
func HttpPostJSON(url string, payload interface{}, dest interface{}) error {
	buf, e := json.Marshal(payload)
	if e != nil {
		return errorx.Wrap(e)
	}

	req, e := http.NewRequest("POST", url, bytes.NewReader(buf))
	if e != nil {
		return errorx.Wrap(e)
	}
	req.Header.Set("Content-Type", "application/json")
	resp, e := client.Do(req)
	if e != nil {
		return errorx.Wrap(e)
	}

	if resp == nil {
		return errorx.NewFromString("resp nil")
	}
	if resp.Body == nil {
		return errorx.NewFromString("resp.Body nil")
	}

	defer resp.Body.Close()
	resBuf, e := ioutil.ReadAll(resp.Body)
	if e != nil {
		return errorx.Wrap(e)
	}

	if e := json.Unmarshal(resBuf, dest); e != nil {
		return errorx.Wrap(e)
	}

	if resp.StatusCode != 200 {
		return errorx.NewFromString(StringMaxLen(200, resBuf))
	}

	return nil
}

func StringMaxLen(max int, buf []byte) string {
	if len(buf) == 0 {
		return ""
	}
	if max >= len(buf) {
		return string(buf)
	}
	return string(buf[:max])
}
